﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Configuration;
using System.Net;

using System.Windows.Forms;

namespace KSOAPlus
{
    class Common
    {
        public static string username;
        public static string EnterpriseName = ConfigurationManager.AppSettings["EnterpriseName"].ToString();        
        public  static string rightcopy="© 2019 Sitaier(QQ:613329777) All Rights Reserved.";

        public string ServerURL = ConfigurationManager.AppSettings["ServerURL"].ToString();

        #region 日志管理
        /// <summary>
        /// 生成日志文件
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="isdebug"></param>
        public void WriteLog(string msg, bool isdebug)
        {
            string text = AppDomain.CurrentDomain.BaseDirectory;
            text = Path.Combine(text, "log");
            if (!Directory.Exists(text))
            {
                Directory.CreateDirectory(text);
            }
            if (isdebug)
            {
                text = Path.Combine(text, "debug");
                if (!Directory.Exists(text))
                {
                    Directory.CreateDirectory(text);
                }
            }
            text = Path.Combine(text, DateTime.Now.ToString("yyyyMMdd") + ".txt");
            if (!File.Exists(text))
            {
                File.CreateText(text).Close();
            }
            StreamWriter streamWriter = new StreamWriter(text, true, Encoding.UTF8);
            if (isdebug)
            {
                streamWriter.WriteLine("--------------------------------------------------------------------------------------------------------------------------------");
            }
            streamWriter.WriteLine("{0}  {1}", DateTime.Now.ToString("yyyyMMdd HH:mm:ss"), msg);
            if (isdebug)
            {
                streamWriter.WriteLine("--------------------------------------------------------------------------------------------------------------------------------");
            }
            streamWriter.Flush();
            streamWriter.Close();
        }
        /// <summary>
        /// 清理日志文件
        /// </summary>
        public void ClearLog()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
            if (Directory.Exists(path))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(path);
                FileInfo[] files = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories);
                FileInfo[] array = files;
                for (int i = 0; i < array.Length; i++)
                {
                    FileInfo fileInfo = array[i];
                    if (DateTime.Now.Subtract(fileInfo.CreationTime).Days > 30)
                    {
                        File.Delete(fileInfo.FullName);
                    }
                }
            }
        }
        #endregion

        #region 账号密码加解密
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="txtStr"></param>
        /// <returns></returns>
        public static string Decrypt(string txtStr)
        {
            string[] keyA = new string[6];
            string[] keyB = new string[6];
            keyA[0] = "wa6j1c";
            keyA[1] = "fblrk7";
            keyA[2] = "mg9q0s";
            keyA[3] = "vu3zth";
            keyA[4] = "po4xy2";
            keyA[5] = "ni5d8e";

            keyB[0] = "ke3wms";
            keyB[1] = "jnx9i8";
            keyB[2] = "dpqzl6";
            keyB[3] = "vyg1bh";
            keyB[4] = "7a4c2f";
            keyB[5] = "u5rto0";
            try
            {
                string text2 = A(txtStr.ToLower(), keyA);
                int i = 0;
                for (int k = 0; k <= 2; k++)
                {
                    i = i * 6 + int.Parse(text2.Substring(k, 1));
                }
                text2 = text2.Substring(3, i);
                string result = jdMethod_if(text2, keyB);
                return result;
            }
            catch (Exception e)
            {
                string result = "Error：" + e.Message;
                return result;
            }
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="txtStr"></param>
        /// <returns></returns>
        public static string Encrypt(string txtStr)
        {
            string[] keyA = new string[6];
            string[] keyB = new string[6];
            keyA[0] = "wa6j1c";
            keyA[1] = "fblrk7";
            keyA[2] = "mg9q0s";
            keyA[3] = "vu3zth";
            keyA[4] = "po4xy2";
            keyA[5] = "ni5d8e";

            keyB[0] = "ke3wms";
            keyB[1] = "jnx9i8";
            keyB[2] = "dpqzl6";
            keyB[3] = "vyg1bh";
            keyB[4] = "7a4c2f";
            keyB[5] = "u5rto0";
            try
            {
                string text2 = A(txtStr.ToLower(), keyB);
                int i = text2.Length;
                for (int k = 0; k <= 2; k++)
                {
                    text2 = (i % 6).ToString() + text2;
                    i = i / 6;
                }
                string result = "";
                Random r = new Random();
                for (int n = 0; text2.Length < 60; n++)
                {
                    text2 = text2 + r.Next(6).ToString();
                    result = jdMethod_if(text2, keyA);
                }
                return result;
            }
            catch (Exception e)
            {
                string result = "Error：" + e.Message;
                return result;
            }
        }

        public static string A(string txtStr, string[] keyA)
        {
            string str = "";
            string str2 = "";

            for (int i = 0; i < txtStr.Length; i++)
            {
                for (int j = 0; j < 6; j++)
                {
                    int k = keyA[j].IndexOf(txtStr.Substring(i, 1)) + 1;
                    if (k > 0)
                    {
                        str += j.ToString();
                        str2 = (k - 1).ToString() + str2;
                        break;
                    }
                }
            }
            string text2 = str + str2;
            return text2;
        }
        public static string jdMethod_if(string txtStr, string[] keyB)
        {
            string result = "";
            if (txtStr.Length % 2 == 1)
            {
                result = "";
            }
            else
            {
                for (int k = 0; k < txtStr.Length / 2; k++)
                {
                    result += keyB[str2ASCII(txtStr.Substring(k, 1)) - str2ASCII("0")].Substring(str2ASCII(txtStr.Substring(txtStr.Length - k - 1, 1)) - str2ASCII("0"), 1);
                }
            }
            return result;
        }
        #endregion

        #region 文件文件夹判断创建
        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="fullName">文件全名称（路径和文件名）</param>
        /// <returns></returns>
        public bool fileExist(string fullName)
        {
            bool response = false;
            if (File.Exists(fullName))
            {
                response = true;
            }
            return response;
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="fullName">文件全名称（路径和文件名）</param>
        public void fileCreate(string fullName)
        {
            File.Create(fullName);
        }

        /// <summary>
        /// 判断文件夹是否存在
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public bool folderExist(string path)
        {
            bool response = false;

            if (Directory.Exists(path))
            {
                response = true;
            }
            return response;
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="path">路径</param>
        public void folderCreate(string path)
        {
            Directory.CreateDirectory(path);
        }
        #endregion

        #region 使DataGridView的列自适应宽度
        /// <summary>
        /// 使DataGridView的列自适应宽度
        /// </summary>
        /// <param name="dgViewFiles"></param>
        public void AutoSizeColumn(DataGridView dgViewFiles)
        {
            int width = 0;
            //使列自使用宽度
            //对于DataGridView的每一个列都调整
            for (int i = 0; i < dgViewFiles.Columns.Count; i++)
            {
                //将每一列都调整为自动适应模式
                dgViewFiles.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                //记录整个DataGridView的宽度
                width += dgViewFiles.Columns[i].Width;
            }
            //判断调整后的宽度与原来设定的宽度的关系，如果是调整后的宽度大于原来设定的宽度，
            //则将DataGridView的列自动调整模式设置为显示的列即可，
            //如果是小于原来设定的宽度，将模式改为填充。
            if (width > dgViewFiles.Size.Width)
            {
                dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            }
            else
            {
                dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
        }
        #endregion

        /// <summary>
        /// 字符转ASCII
        /// </summary>
        /// <param name="xmlStr"></param>
        /// <returns></returns>
        public static int str2ASCII(string xmlStr)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(xmlStr);
            return (int)bytes[0];
        }

        public bool Up(string webUrl, string CaptureToBase64, string corpid, string typeid, string endrq, int I)
        {
            try
            {
                string postData = "corpid=" + corpid + "&typeid=" + typeid + "&endrq=" + endrq + "&UploadFile=" + System.Web.HttpUtility.UrlEncode(CaptureToBase64);

                var webclient = new WebClient();
                webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                byte[] buffer = webclient.UploadData(webUrl, "POST", byteArray);
                var msg = Encoding.UTF8.GetString(buffer);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #region 更新APP.config信息
        ///<summary> 
        ///更新连接字符串  
        ///</summary> 
        ///<param name="newName">连接字符串名称</param> 
        ///<param name="newConString">连接字符串内容</param> 
        ///<param name="newProviderName">数据提供程序名称</param> 
        public void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
        {
            //指定config文件读取
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);

            bool exist = false; //记录该连接串是否已经存在  
            //如果要更改的连接串已经存在  
            if (config.ConnectionStrings.ConnectionStrings[newName] != null)
            {
                exist = true;
            }
            // 如果连接串已存在，首先删除它  
            if (exist)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            //新建一个连接字符串实例  
            ConnectionStringSettings mySettings =
                new ConnectionStringSettings(newName, newConString, newProviderName);
            // 将新的连接串添加到配置文件中.  
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("connectionStrings");
        }
        ///<summary> 
        ///更新连接字符串  
        ///</summary> 
        ///<param name="newName">连接字符串名称</param> 
        ///<param name="newConString">连接字符串内容</param> 
        ///<param name="newProviderName">数据提供程序名称</param> 
        public void UpdateappSettingsConfig(string newKey, string newValue)
        {
            //指定config文件读取
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);

            bool exist = false; //记录该连接串是否已经存在  
            //如果要更改的连接串已经存在  

            if (config.AppSettings.Settings[newKey] != null)
            {
                exist = true;
            }
            // 如果连接串已存在，首先删除它  
            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            //新建一个连接字符串实例  
            KeyValueConfigurationElement mySettings =
                new KeyValueConfigurationElement(newKey, newValue);
            // 将新的连接串添加到配置文件中.  
            config.AppSettings.Settings.Add(mySettings);
            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("AppSettings");
        }
        #endregion
    }
}
